use std::{fs::OpenOptions, io::Write, process::Command};

fn main() {
    println!("cargo:rerun-if-changed=NULL");
    let mut asm = OpenOptions::new()
        .write(true)
        .create(true)
        .open("code.s")
        .unwrap();
    let h = ".code16\n\
        .section .text\n\
        .org 0x00\n";
    let ivt = (0..256).into_iter().fold(String::new(), |s, i| {
        format!("{}.word 0x0000\n.word {}\n", s, (0x5000 + i * 0x20)>>4)
    });
    let int_handle = (0..256).into_iter().fold(String::new(), |s: String, i| {
        format!("{}.org {}\nmovw ${},0x9000\niret\n", s, 0x5000 + i * 0x20, i)
    });
    let real_code = ".org 0x7c00\n\
        sti\n\
        jmp .\n
    ";
    asm.write_all(h.as_bytes()).unwrap();
    asm.write_all(ivt.as_bytes()).unwrap();
    asm.write_all(int_handle.as_bytes()).unwrap();
    asm.write_all(real_code.as_bytes()).unwrap();

    let c = Command::new("make").arg("all").spawn().unwrap();
    let o = c.wait_with_output().unwrap();
    println!("{:?}", String::from_utf8(o.stderr));
    println!("{:?}", String::from_utf8(o.stdout));
}
